package com.tieshan.smartwindow.widget

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.text.TextUtils
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.RequiresApi
import com.tencent.mmkv.MMKV
import com.tieshan.smartwindow.R
import com.tieshan.smartwindow.other.CnUtil
import com.tieshan.smartwindow.other.FileConfig
import com.tieshan.smartwindow.other.FileUtil
import com.tieshan.smartwindow.other.pisutil.CRC16Utils
import com.tieshan.smartwindow.other.pisutil.UDPData
import com.tieshan.smartwindow.other.pisutil.UDPDataUtil
import kotlinx.android.synthetic.main.layout_maintop_left.view.*
import kotlinx.android.synthetic.main.layout_maintop_right.view.*
import kotlinx.android.synthetic.main.layout_maintop_right.view.ll_arrive
import kotlinx.android.synthetic.main.layout_maintop_right.view.ll_offline
import kotlinx.android.synthetic.main.layout_maintop_right.view.ll_routing
import kotlinx.android.synthetic.main.layout_maintop_right.view.ll_station
import kotlinx.android.synthetic.main.layout_maintop_right.view.mtext_cn
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_arriveendstation_cn
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_arriveendstation_en
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_arrivenext_cn
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_arrivenext_en
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_endstation_cn
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_endstation_en
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_hour
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_min
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_point
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_startstation_cn
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_startstation_en
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_stationnumber
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_stationstartend_cn
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_stationstartend_en
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_week_cn
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_week_en
import kotlinx.android.synthetic.main.layout_maintop_right.view.tv_year
import timber.log.Timber
import java.util.*
import kotlin.time.ExperimentalTime


/**
 * author : Hleo
 * time   : 2022/2/9
 * desc   : 主页面顶部PIS信息控件
 */
@ExperimentalStdlibApi
@OptIn(ExperimentalTime::class)
class MainTopView_Right @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
    var view: View? = null

    //当前站点  下一站点   当前英文站点  下一英文站点
    var nowStation = ""
    var nextStation = ""
    var nowEnStation = ""
    var nextEnStation = ""
//    var testlistener: isTestListener? = null

    //上一次推送的起始站点和站点状态
    var oldNowStationId = 0
    var oldNextStationId = 0
    var oldStationStatus = 0
    var leavelistener: isLeaveListener? = null
    //是否是终点站到站
    var hasendOn=true
    //是否是离站
    var hasstartLeave=true
    init {
        view = inflate(context, R.layout.layout_maintop_right, null)
        val params = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
        view!!.layoutParams = params
        addView(view)

    }

    //设置时间
    fun setTime(data: UDPData) {
        if (data!!.timeSpeed!!.year == null || data!!.timeSpeed!!.year.toString().length != 4) return
        if (data!!.timeSpeed!!.month == null || data!!.timeSpeed!!.month > 12||data!!.timeSpeed!!.month<  0 || data!!.timeSpeed!!.month.toString().length > 2) return
        if (data!!.timeSpeed!!.day == null || data!!.timeSpeed!!.day > 31||data!!.timeSpeed!!.day<  0|| data!!.timeSpeed!!.day.toString().length > 2) return
        if (data!!.timeSpeed!!.hour == null || data!!.timeSpeed!!.hour > 24||data!!.timeSpeed!!.hour<  0 || data!!.timeSpeed!!.hour.toString().length > 2) return
        if (data!!.timeSpeed!!.min == null || data!!.timeSpeed!!.min > 60 ||data!!.timeSpeed!!.min<  0 || data!!.timeSpeed!!.min.toString().length > 2) return
        val hour = data.timeSpeed!!.hour
        val min = data.timeSpeed!!.min
        val year = data.timeSpeed!!.year
        val month = data.timeSpeed!!.month
        val day = data.timeSpeed!!.day
        if (hour>=0&&hour<=60) {
            var hours = String.format("%02d", hour)
            if (tv_hour.text != hours)
                tv_hour.text = hours
        }
        if (min>=0&&min<=60) {
            var mins = String.format("%02d", min)
            if (tv_min.text != mins)
                tv_min.text = mins
        }
        if (month >= 0 && day >= 0 && month <= 12 && day <= 31&&year>2000&&year<2100) {
            var years = "${year}.${String.format("%02d", month)}.${String.format("%02d", day)}"
            if (tv_year.text != years) {
                tv_year.text = years
                setWeek(data)
            }
        }
    }

    fun setPoint(){
        tv_point.visibility =
            if (tv_point.visibility == View.INVISIBLE) View.VISIBLE else View.INVISIBLE
    }

    //设置星期
    @SuppressLint("SetTextI18n")
    private fun setWeek(data: UDPData) {
        val calendar = Calendar.getInstance()
        calendar.set(Calendar.YEAR,data.timeSpeed!!.year)
        calendar.set(Calendar.MONTH,data.timeSpeed!!.month-1)
        calendar.set(Calendar.DAY_OF_MONTH,data.timeSpeed!!.day)
        calendar.set(Calendar.HOUR_OF_DAY,data.timeSpeed!!.hour)
        calendar.set(Calendar.MINUTE,data.timeSpeed!!.min)
        calendar.set(Calendar.SECOND,data.timeSpeed!!.sec)
        val week = calendar[Calendar.DAY_OF_WEEK]
        when (week) {
            1 -> {
                tv_week_cn.text = "星期天"
                tv_week_en.text = "Sunday"
            }
            2 -> {
                tv_week_cn.text = "星期一"
                tv_week_en.text = "Monday"
            }
            3 -> {
                tv_week_cn.text = "星期二"
                tv_week_en.text = "Tuesday"
            }
            4 -> {
                tv_week_cn.text = "星期三"
                tv_week_en.text = "Wednesday"
            }
            5 -> {
                tv_week_cn.text = "星期四"
                tv_week_en.text = "Thursday"
            }
            6 -> {
                tv_week_cn.text = "星期五"
                tv_week_en.text = "Friday"
            }
            7 -> {
                tv_week_cn.text = "星期六"
                tv_week_en.text = "Saturday"
            }
        }
    }

    fun showDisconnctContent() {
        ll_routing.visibility = View.GONE
        ll_arrive.visibility = View.GONE
        ll_station.visibility = View.GONE
        ll_offline.visibility=View.VISIBLE
    }

    //更新站点显示
    @SuppressLint("SetTextI18n")
    fun setAtStation(data: UDPData) {
        ll_offline.visibility = View.GONE
        //接收到发送的数据以后，重置定时任务
        updateData(data)
    }


    var jihuoCode=0
    @SuppressLint("SetTextI18n")
    private fun updateData(data: UDPData) {
        ll_station.visibility=View.VISIBLE
        try {
            when (CRC16Utils.bytesToHexString(data.functionCode)) {
                //列车文本信息
                UDPDataUtil.functionCode.textInVisibleCode, UDPDataUtil.functionCode.textBackCode, UDPDataUtil.functionCode.textThinCode -> {
                    mtext_cn.text = data.textInfo!!.content
                }
                //列车心跳连接
                UDPDataUtil.functionCode.carNumberCode -> {
                    var carnumer=data.carnumberInfo?.carNumber
                    if (TextUtils.isEmpty(carnumer))
                        return
                    if (carnumer!!.length<=0)
                        return
                    tv_stationnumber.setText(carnumer)
//                    testlistener!!.Test(data.carnumberInfo?.isTest!!)
                }

                //中文站点信息
                UDPDataUtil.functionCode.cnStationCode -> {
                    tv_stationstartend_cn.visibility = View.VISIBLE
                    val stationlist = data.cnStationList
                    var startstationName=stationlist!![0].staionName
                    var endstationName=stationlist!![stationlist.size - 1].staionName
                    if (!CnUtil.isPureChinese(startstationName)&&!CnUtil.isPureChinese(endstationName))
                        return
                    var stationName="$startstationName - $endstationName"
                    setCnTextStyleStartEnd(tv_stationstartend_cn,stationName)
                }
                //英文站点信息
                UDPDataUtil.functionCode.enStationCode -> {
                    tv_stationstartend_en.visibility = View.VISIBLE
                    val stationlist = data.enStationList
                    var enstartstationName=stationlist!![0].staionName
                    var emendstationName=stationlist!![stationlist.size - 1].staionName
                    if (!CnUtil.isEnglishOnly(enstartstationName)&&!CnUtil.isEnglishOnly(emendstationName))
                        return
                    var stationName= "$enstartstationName - $emendstationName"
                   setEnTextStyleStartEnd(tv_stationstartend_en,stationName)
                }
                //列车位置状态
                UDPDataUtil.functionCode.trainlocationCode -> {
                    if (data.cnStationList == null || data.cnStationList!!.size == 0 || data.enStationList == null || data.enStationList!!.size == 0 || data.location == null)
                        return
                    var stationdatas = data.cnStationList
                    var enStationDatas = data.enStationList
                    //判断是否是当前站点
//                    if (oldNowStationId == data.location!!.nowLocationId && oldNextStationId == data.location!!.nextLocationId && oldStationStatus == data.location!!.status) {
//                        isSameStation = true
//                    } else {
//                        isSameStation = false
                    oldNowStationId = data.location!!.nowLocationId
                    oldNextStationId = data.location!!.nextLocationId
                    oldStationStatus = data.location!!.status
//                    }
                    if (stationdatas!!.size != 0) {
                        for (index in 0..stationdatas.size - 1) {
                            if (stationdatas[index].id == data.location!!.nowLocationId)
                                nowStation = stationdatas[index].staionName
                            if (stationdatas[index].id == data.location!!.nextLocationId)
                                nextStation = stationdatas[index].staionName
                        }
                    }
                    //如果没有英文站点，则显示中文站点
                    if (enStationDatas!!.size == 0) {
                        enStationDatas = arrayListOf()
                        for (index in stationdatas.indices) {
                            val bean = UDPData.EnStationBean()
                            bean.staionName = stationdatas[index].staionName
                            bean.id = stationdatas[index].id
                            enStationDatas.add(bean)
                        }
                    }
                    if (enStationDatas.size != 0) {
                        for (index in 0..enStationDatas.size - 1) {
                            if (enStationDatas[index].id == data.location!!.nowLocationId)
                                nowEnStation = enStationDatas[index].staionName
                            if (enStationDatas[index].id == data.location!!.nextLocationId)
                                nextEnStation = enStationDatas[index].staionName
                        }
                    }
                    ll_arrive.visibility = View.GONE
                    ll_routing.visibility=View.GONE
                    when (data.location!!.status) {
                        1 -> {
                            ll_arrive.visibility = View.VISIBLE
                            tv_arrivenext_cn.text = "下一站"
                            tv_arrivenext_en.text = "Next Station"
                            setCnTextStyle(tv_arriveendstation_cn,nextStation)
                            setEnTextStyle(tv_arriveendstation_en,nextEnStation)
                            try {
                                if (stationdatas[0].id == data.location!!.nowLocationId&&hasstartLeave){
                                    hasstartLeave=false
                                    hasendOn=true
                                    leavelistener!!.leaveListener()
                                }
                            }catch (e:Exception){
                            }
                        }
                        2 -> {
                            ll_routing.visibility=View.VISIBLE
                            setRoutingTextStyle(tv_startstation_cn,nowStation)
                            setRoutingTextStyle(tv_endstation_cn,nextStation)
                            setEnRoutingTextStyle(tv_startstation_en,nowEnStation)
                            setEnRoutingTextStyle(tv_endstation_en,nextEnStation)
                        }
                        3 -> {
                            ll_arrive.visibility = View.VISIBLE
                            tv_arrivenext_cn.text = "前方到站"
                            tv_arrivenext_en.text = "Next Station"
                            setCnTextStyle(tv_arriveendstation_cn,nextStation)
                            setEnTextStyle(tv_arriveendstation_en,nextEnStation)
                        }
                        4 -> {
                            ll_arrive.visibility = View.VISIBLE
                            try {
                                if (stationdatas[stationdatas.size-1].staionName == nowStation&&hasendOn){
                                    tv_arrivenext_cn.text = "终点站"
                                    tv_arrivenext_en.text = "Terminus Station"
                                    hasendOn=false
                                    hasstartLeave=true
                                    leavelistener!!.endListener()
                                }else{
                                    tv_arrivenext_cn.text = "当前到站"
                                    tv_arrivenext_en.text = "This Station"
                                    setCnTextStyle(tv_arriveendstation_cn,nowStation)
                                    setEnTextStyle(tv_arriveendstation_en,nowEnStation)
                                }
                            }catch (e:Exception){
                                Timber.e("异常二，${e.message}")
                            }
                        }
                    }
                }
            }
        } catch (e: Exception) {
        }
    }

    //途中文字显示
    fun setRoutingTextStyle(textView:TextView,content: String){
        var proportion=36f
        if (content.length<=5)
            proportion=36f
        else  if (content.length>5&&content.length<=7)
            proportion=28f
        else  if (content.length>7&&content.length<=10)
            proportion=20f
        else  if (content.length>10&&content.length<=14f)
            proportion=15f
        else
            proportion=12f
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, proportion)
        if (CnUtil.isPureChinese(content) && !textView.text.toString().equals(content))
            textView.text = content
    }

    //途中英文文字显示
    fun setEnRoutingTextStyle(textView:TextView,content: String){
        var proportion=10f
        if (content.length<=22)
            proportion=18f
        else  if (content.length>22&&content.length<=27)
            proportion=14f
        else  if (content.length>27)
            proportion=10f
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, proportion)
        if (CnUtil.isEnglishOnly(content) && !textView.text.toString().equals(content))
            textView.text = content
    }

    //设置文字文本状态
    /**
     * @param content 文本内容
     * @param proportion 文本缩放比例
     * @param start  开始位置
     * @param end  结束位置
     */
    fun setCnTextStyleStartEnd(textView: TextView, content: String) {
        var proportion = 36f
        if (content.length <= 12)
            proportion = 36f
        else if (content.length > 12 && content.length <= 14)
            proportion = 28f
        else if (content.length > 14 && content.length <= 19)
            proportion = 20f
        else if (content.length > 19 && content.length <= 26f)
            proportion = 15f
        else
            proportion = 12f
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, proportion)
        if (!textView.text.toString().equals(content))
            textView.text = content
    }

    fun setEnTextStyleStartEnd(textView: TextView, content: String) {
        var proportion = 18f
        if (content.length <= 37)
            proportion = 18f
        else if (content.length > 37 && content.length <= 48)
            proportion = 15f
        else
            proportion = 10f
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, proportion)
        if (!textView.text.toString().equals(content))
            textView.text = content
    }


    //设置文字文本状态
    /**
     * @param content 文本内容
     * @param proportion 文本缩放比例
     * @param start  开始位置
     * @param end  结束位置
     */
    fun setCnTextStyle(textView:TextView,content: String) {
        var proportion=36f
        if (content.length<=12)
            proportion=36f
        else  if (content.length>12&&content.length<=14)
            proportion=28f
        else  if (content.length>14&&content.length<=19)
            proportion=20f
        else  if (content.length>19&&content.length<=26f)
            proportion=15f
        else
            proportion=12f
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, proportion)
        if (CnUtil.isPureChinese(content) && !textView.text.toString().equals(content))
            textView.text = content    }

    fun setEnTextStyle(textView:TextView,content: String) {
        var proportion=18f
        if (content.length<=37)
            proportion=18f
            else    if (content.length>37&&content.length<=48)
            proportion=15f
        else
            proportion=10f
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, proportion)
        if (CnUtil.isEnglishOnly(content) && !textView.text.toString().equals(content))
            textView.text = content    }

    //测试模式
    interface isTestListener {
        fun Test(isTest: Boolean)
    }

    //注意测试模式
//    topView_left.testlistener = object : MainTopView_Left.isTestListener {
//        override fun Test(isTest: Boolean) {
//            if (isTest) {
//                hasTest = false
//                iv_test.visibility = View.VISIBLE
//                if (testIndex == 0) iv_test.setBackgroundColor(
//                    this@MainActivity.resources.getColor(
//                        R.color.red
//                    )
//                )
//                else if (testIndex == 2) iv_test.setBackgroundColor(
//                    this@MainActivity.resources.getColor(
//                        R.color.green
//                    )
//                )
//                else if (testIndex == 4) iv_test.setBackgroundColor(
//                    this@MainActivity.resources.getColor(
//                        R.color.blue
//                    )
//                )
//            } else {
//                hasTest = true
//                testIndex = 0
//                iv_test.visibility = View.GONE
//            }
//        }
//    }
//    topView_right.testlistener = object : MainTopView_Right.isTestListener {
//        override fun Test(isTest: Boolean) {
//            if (isTest) {
//                hasTest = falseF
//                iv_test.visibility = View.VISIBLE
//                if (testIndex == 0) iv_test.setBackgroundColor(
//                    this@MainActivity.resources.getColor(
//                        R.color.red
//                    )
//                )
//                else if (testIndex == 2) iv_test.setBackgroundColor(
//                    this@MainActivity.resources.getColor(
//                        R.color.green
//                    )
//                )
//                else if (testIndex == 4) iv_test.setBackgroundColor(
//                    this@MainActivity.resources.getColor(
//                        R.color.blue
//                    )
//                )
//            } else {
//                hasTest = true
//                testIndex = 0
//                iv_test.visibility = View.GONE
//            }
//        }
//    }

    //首站离站，则开始显示屏幕页面
    interface isLeaveListener{
        fun leaveListener()
        fun endListener()
    }
}